import axios from 'axios'
import router from '@/libs/router'
import { useOperatorStore } from '@/libs/store'
import { RequestConfig } from '@/libs/config'
import { EmptyUtil, MsgUtil } from '@/utils'

// 创建一个封装后在请求对象
export class RequestCore {
    // 初始化参数封装
    protected getAxiosInit() {
        const { baseURL, timeout } = RequestConfig
        return { baseURL, timeout }
    }

    // 响应码转换封装
    protected formatCode(data, status: number) {
        const { successCode, statusName } = RequestConfig
        // 若data.code存在，覆盖默认code 否则使用返回数据的状态码
        if (data && data[statusName]) return successCode.includes(data[statusName]) ? 200 : data[statusName]
        return successCode.includes(status) ? 200 : status
    }

    // 格式化错误返回请求消息
    protected formatErrorMsg(data, code: number, content: string) {
        const { messageName, errMsg } = RequestConfig
        if (data && data[messageName]) return data[messageName]
        if (data && errMsg[code]) return errMsg[code]
        return content
    }

    // 设置请求配置方法
    protected setRequestConfig(config) {
        const { token } = useOperatorStore()
        const { tokenCode, tokenPrefix } = RequestConfig
        const tokenValue = EmptyUtil.isNotEmptyString(tokenPrefix) ? `${tokenPrefix}${token}` : token
        if (token) config.headers[tokenCode] = tokenValue
        return config
    }

    // 响应拦截器封装方法

    protected async handleData(response) {
        const { data, status, statusText } = response
        const { removeAll } = useOperatorStore()
        const resCode = this.formatCode(data, status)
        const content = this.formatErrorMsg(data, resCode, statusText)

        switch (resCode) {
            case 200:
                return data
            case 4000:
                // 登录超时
                await router.replace({path: '/login' })
                MsgUtil.message(content, 'error')
                removeAll()
                window.location.reload()
                break ;




            case 4001:
                // 没有权限 跳转到没有权限的页面
                MsgUtil.notify('数据请求异常', content, 'error')
                await router.push({ path: '/error/401' })
                return Promise.reject(data)

            case 4002:
                const handler=()=>router.replace({path: '/login' })
                MsgUtil.alert("操作失败",content,'error',handler)
                return Promise.reject(data)
            default:
                MsgUtil.notify('操作失败', content, 'error')
                return Promise.reject(data)
        }
    }

    // 响应异常处理方法封装
    protected errorHandle(error) {
        const { response } = error
        console.log(response)
        if (response === undefined) {
            const content =
                '数据请求异常:连接后台接口失败，可能由以下原因造成：后端不支持跨域CORS、接口地址不存在、请求超时等，请联系管理员排查后端接口问题 '
            MsgUtil.message(content, 'error')
        } else {
            return this.handleData(response)
        }
    }

    public instance = axios.create(this.getAxiosInit())

    // 创建构造方法
    constructor() {
        try {
            // 请求拦截器
            this.instance.interceptors.request.use(this.setRequestConfig, error => Promise.reject(error))
            // 响应拦截器
            this.instance.interceptors.response.use(
                response => this.handleData(response),
                error => this.errorHandle(error)
            )
        } catch (e) {
            console.error(e)
        }
    }
}
